package com.my.content.anday44_bluetooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;

public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener{

    private TextView tvDevice;
    //Android里面对蓝牙的所有操作都由BluetoothAdapter来完成
    private BluetoothAdapter mBluetoothAdapter;
    private ArrayAdapter<String> mAdapter;
    private ArrayAdapter<String> dialogAdapter;
    //用来存放广播接收器中扫描到的蓝牙信息
    private Set<BluetoothDevice> newDevices;
    private FoundDeviceReceiver mReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //文本
        tvDevice = (TextView) findViewById(R.id.tv_device);
        //ListView
        ListView mLv = (ListView) findViewById(R.id.lv_devices);
        //对勾按钮
        CheckBox cbEnable =  (CheckBox) findViewById(R.id.cb_enable);
        cbEnable.setOnCheckedChangeListener(this);
        //检查蓝牙是否可用
        checkBlueToothEnable();
        //创建适配器
        mAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1);
        //设置适配器
        mLv.setAdapter(mAdapter);

        newDevices = new HashSet<>();

        //如何搜索附近的蓝牙设备？----》广播接收器
        IntentFilter filter = new IntentFilter();
        //用于发现蓝牙设备
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        mReceiver = new FoundDeviceReceiver();
        //注册广播接收器
        registerReceiver(mReceiver,filter);
    }
    //运行自己的设备被别的设备搜索到
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            Intent intent=new Intent();
            //可以被别的设备发现
            intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            //自己的设备在多长时间内可以被别的设备发现,0--3600秒.默认120秒.
            intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,60);
            startActivity(intent);
        }
    }
    //缺什么补什么，用来发现蓝牙设备的广播接收器
    class FoundDeviceReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if(BluetoothDevice.ACTION_FOUND.equals(intent.getAction())) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                //数据源添加到适配器
                dialogAdapter.add("设备名称："+device.getName()+"\n设备地址："+device.getAddress()+"\n绑定状态："+device.getBondState());
                newDevices.add(device);
            }
        }
    }
    //监测手机是否支持蓝牙功能
    private void checkBlueToothEnable() {
        //得到一个蓝牙适配器
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        //判断是否有蓝牙功能
        if(mBluetoothAdapter == null){
            tvDevice.setText("该设备不支持蓝牙功能");
        }else {
            tvDevice.setText("该设备支持蓝牙功能");
            if (!mBluetoothAdapter.isEnabled()) {
                new AlertDialog.Builder(this)
                        .setTitle("提示")
                        .setMessage("蓝牙设备未打开，是否打开蓝牙")
                        .setNegativeButton("取消", null)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //打开蓝牙功能，隐式意图跳转到设置界面，此处不需要跳转
                                Intent intent = new Intent();
                                //设置Action为请求功能可用
                                intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                                //打开蓝牙之后还使用回调所以用startActivityForResult
                                startActivityForResult(intent, 0);
                                //处理完后执行onActivityResult
                            }
                        })
                        .setCancelable(false)//不可以被取消
                        .show();//展示出来
            }else {
                getBoundDeviceInfo();
            }
        }
    }


    //搜索附近的蓝牙设备
    public void searchBT(View view) {
        //搜索过程中一个一个添加到适配器，要想实现这一点要用广播接收器
        dialogAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1);
        //弹一个对话框
        new AlertDialog.Builder(this)
                .setTitle("设备搜索中...")
                .setAdapter(dialogAdapter, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            //和发现的设备配对
                            BluetoothDevice device = (BluetoothDevice) newDevices.toArray()[which];
                            //当蓝牙设备未绑定执行
                            if(device.getBondState() == BluetoothDevice.BOND_NONE) {
                                //用反射进行绑定
                                //device是类的对象，得到类的字节码
                                Class<? extends BluetoothDevice> clazz = device.getClass();
                                //得到creatBond方法,执行绑定方法
                                Method creatBond = clazz.getDeclaredMethod("creatBond");
                                creatBond.setAccessible(true);
                                boolean flag = (boolean) creatBond.invoke(device);
                                if (flag) {
                                    Toast.makeText(MainActivity.this, "绑定成功", Toast.LENGTH_SHORT).show();
                                }
                            }else{
                                //取消之前的扫描任务
                            mBluetoothAdapter.cancelDiscovery();
                            }
                        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                            e.printStackTrace();
                        }
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if(mBluetoothAdapter.isDiscovering()){//判断是否正在扫描新设备
                    //取消扫描任务
                    mBluetoothAdapter.cancelDiscovery();
                }
            }
        }).show();
        //开始扫描
        mBluetoothAdapter.startDiscovery()  ;
    }

    //回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == 0 && resultCode == RESULT_OK){//证明回调可以用
            //方法：获取之前已经配对的蓝牙设备信息
                getBoundDeviceInfo();
        }
    }
    //获取之前已经配对的蓝牙设备信息
    public void getBoundDeviceInfo() {
        //得到所有已配置的蓝牙设备
        Set<BluetoothDevice> bondedDevices = mBluetoothAdapter.getBondedDevices();
        for(BluetoothDevice device : bondedDevices){//遍历信息
            //名称
            String name = device.getName();
            //地址（物理地址）
            String address = device.getAddress();
            //绑定状态
            int bondState = device.getBondState();
        //拿到信息在ListView里展示，这里是适配器的数据源
            mAdapter.add("设备名称："+name+"\n设备地址："+address+"\n绑定状态："+bondState);
            //清单文件里设置
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mReceiver != null){
            //取消注册
            unregisterReceiver(mReceiver);
        }
        //在程序退出的时候关闭蓝牙功能
        if(mBluetoothAdapter!=null){
            mBluetoothAdapter.disable();
        }
    }
}
